package redis

import (
	"cs/src/config"
	"cs/src/libs/logs"
	"errors"
	"github.com/go-redis/redis"
	"strconv"
)

var RedisClient *redis.Client

func init() {
	redisConfig := redisConfig()

	// string转int
	redisDb, _ := strconv.Atoi(redisConfig["redis_db"])

	RedisClient = redis.NewClient(&redis.Options{
		Addr:     redisConfig["redis_host"] + ":" + redisConfig["redis_port"],
		Password: redisConfig["redis_password"], // no password set
		DB:       redisDb,                       // use default DB
	})

	_, err := RedisClient.Ping().Result()
	if err != nil {
		// 因为连接不上redis是一个致命错误，程序无法执行相关操作，所以应该直接panic
		panic(errors.New("redis连接失败:" + err.Error()))
	} else {
		logs.Info("初始化：redis连接成功")
	}
}

func redisConfig() map[string]string {
	return config.Section("redis")
}
